package com.hmall.common.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UserInterceptor implements HandlerInterceptor {
    //获取请求头的userInfo放到ThreadLocal中
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserContext.removeUser();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userInfo = request.getHeader("user-info");
        if(ObjectUtil.isNotEmpty(userInfo)){
            UserContext.setUser(Long.valueOf(userInfo));
        }
        return true;
    }
}
